<template>
  <div>
    <el-input
      v-if="mutiple"
      type="textarea"
      :autosize="true"
      @click.native="openDialog"
      :value="value[showTag]"
      :disabled="disabled"
    ></el-input>
    <el-input
      v-else
      @click.native="openDialog"
      :value="value[showTag]"
      :disabled="disabled"
    ></el-input>
    <el-dialog
      title="选择测点"
      :visible.sync="selectTagDialog"
      v-if="selectTagDialog"
      width="80%"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form :inline="true">
        <el-form-item label="名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="编码">
          <el-input
            v-model="queryParams.tag"
            placeholder="请输入编码"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            v-loading="selectBtn"
            @click="getSelectData"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        border
        :data="deptOptions"
        @select="handleSelection"
        @select-all="handleSelectAll"
        :header-cell-class-name="cellClass"
        height="40vh"
        :row-key="
          (row) => {
            return row.tag;
          }
        "
        @row-click="handleRowClick"
        ref="table"
        :cell-style="tableCellStyle"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
          :reserve-selection="true"
          :selectable="rowSelectable"
        />
        <el-table-column
          align="center"
          label="名称"
          prop="name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="编码"
          prop="tag"
        ></el-table-column>
      </el-table>

      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getSelectData"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="closeSelectTagDialog"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { pageData } from './tableData.js'
export default {
  props: {
    value: {},
    label: {
      require: true
    },
    id: {
      require: true
    },
    showTag: {
      default: function () {
        return this.label
      }
    },
    disabled: {
      default: false
    },
    mutiple: {
      default: false
    }
  },
  data () {
    return {
      selectTagDialog: false,
      queryParams: {
        name: null,
        tag: null,
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      selectBtn: false,
      deptOptions: [],
      // 使用Map存储所有选中的tag
      selectedMap: new Map(),
      // 选中的项目数组
      selectedItems: []
    }
  },
  computed: {
    // 当前页的选中状态
    currentPageSelected () {
      return this.deptOptions.filter((item) => this.selectedMap.has(item.tag))
    }
  },
  methods: {
    // 全选按钮隐藏
    cellClass () {
      if (!this.mutiple) {
        return 'DisableSelection'
      }
    },
    rowSelectable (row, index) {
      // console.log(row.tag.substring(5))
      // return Number(row.tag.substring(5)) > 15
      return true
      // return row.source === 'red'
    },
    handleSelectAll (selection) {
      console.log('全选事件触发', selection)
      if (this.mutiple) {
        // 通过this.$refs.table.data获取当前页的所有行
        const currentPageRows = this.$refs.table.data
        currentPageRows.forEach((row) => {
          this.selectedMap.set(row.tag, true)
        })
        // 更新选中项目数组
        this.updateSelectedItems()
        // 更新表格选中状态
        this.updateTableSelection()
      }
    },
    // 修改数据行里面的颜色
    tableCellStyle ({ row, rowIndex }) {
      return this.selectedMap.has(row.tag)
        ? { 'background-color': '#fff3e0' }
        : {}
    },
    openDialog () {
      this.selectTagDialog = true
      this.getSelectData()
      // 计算需要回显的数据
      this.handleCheckedData()
    },
    closeSelectTagDialog () {
      if (!this.mutiple && this.selectedItems.length > 0) {
        this.$set(this.value, this.label, this.selectedItems[0].name)
        this.$set(this.value, this.id, this.selectedItems[0].tag)
      }
      if (this.mutiple) {
        const name = this.selectedItems.map((item) => item.name).join('，')
        const id = this.selectedItems.map((item) => item.tag).join(',')
        this.$set(this.value, this.label, name)
        this.$set(this.value, this.id, id)
      }
      this.cancelDialog()
    },
    handleSelection (selection, row) {
      if (this.mutiple) {
        // 多选模式
        if (selection.includes(row)) {
          // 选中
          this.selectedMap.set(row.tag, true)
        } else {
          // 取消选中
          this.selectedMap.delete(row.tag)
        }
        // 更新选中项目数组
        this.updateSelectedItems()
      } else {
        // 单选模式
        this.updateTableSelection()
        this.selectedMap.clear()
        this.selectedMap.set(row.tag, true)
        this.updateSelectedItems()
      }
    },
    handleRowClick (row) {
      if (!row.isCollected) {
        this.$refs.table.toggleRowSelection(row)
      }
      // 调用handleSelection处理选中状态
      const selection = this.$refs.table.selection
      this.handleSelection(selection, row)
    },
    getSelectData () {
      this.selectBtn = true
      // 保存当前选中状态
      const savedSelectedMap = new Map(this.selectedMap)

      // 模拟获取分页数据
      setTimeout(() => {
        const res = pageData(
          this.queryParams.pageNum,
          this.queryParams.pageSize
        )
        this.total = res.total
        this.selectBtn = false
        this.deptOptions = res.data

        // 恢复选中状态
        this.deptOptions.forEach((row) => {
          if (savedSelectedMap.has(row.tag)) {
            this.selectedMap.set(row.tag, true)
          }
        })

        // 更新表格选中状态
        this.updateTableSelection()
      }, 500)
    },
    // 重置
    cancelDialog () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.selectedMap.clear()
      this.selectedItems = []
      this.selectTagDialog = false
    },
    handleCheckedData () {
      this.selectedMap.clear()
      if (this.value.name && this.value.id) {
        const nameArr = this.value.name.split('，')
        const idArr = this.value.id.split(',')
        for (let i = 0; i < nameArr.length; i++) {
          if (nameArr[i] !== '' && idArr[i] !== '') {
            this.selectedMap.set(idArr[i], true)
          }
        }
        this.updateSelectedItems()
      }
    },
    // 更新表格选中状态
    updateTableSelection () {
      this.$nextTick(() => {
        // 清除所有选中状态
        this.$refs.table.clearSelection()

        // 设置当前页的选中状态
        this.deptOptions.forEach((row) => {
          if (this.selectedMap.has(row.tag)) {
            this.$refs.table.toggleRowSelection(row, true)
          }
        })
      })
    },
    // 更新选中项目数组
    updateSelectedItems () {
      // 从selectedMap生成selectedItems
      this.selectedItems = Array.from(this.selectedMap.keys()).map((tag) => {
        // 尝试从当前数据中查找完整信息
        const item = this.deptOptions.find((item) => item.tag === tag)
        return item || { tag, name: tag } // 如果找不到，使用tag作为名称
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-table .DisableSelection .cell .el-checkbox__inner {
  display: none;
  position: relative;
}
::v-deep .el-table .DisableSelection .cell:before {
  content: "";
  position: absolute;
}
</style>
